import React, { Component } from 'react'
import PropTypes from "prop-types"
import {
  Form,
  Input,
  Tree
} from 'antd/lib/index'
import menuList from '../../config/menu_config'

const Item = Form.Item
const { TreeNode } = Tree

// 添加分类的组件
export default class AuthForm extends Component {
  static propTypes = {
    role: PropTypes.object
  }

  constructor (props) {
    super(props)

    const { menus } = this.props.role
    this.state = {
      checkedKeys: menus
    }
  }

  getTreeNodes = (menuList) => {
    return menuList.reduce((pre, item) => {
      pre.push(
        <TreeNode title={item.title} key={item.key}>
          { item.children ? this.getTreeNodes(item.children) : null }
        </TreeNode>
      )
      return pre
    }, [])
  }

  // 选中某个复选框的回调
  onCheck = checkedKeys => {
    console.log('onCheck', checkedKeys)
    this.setState({ checkedKeys })
  }

  // 提供给父组件的 menus
  getMenus = () => this.state.checkedKeys

  componentWillMount () {
    this.treeNodes = this.getTreeNodes(menuList)
  }

  // 根据新传入的 role 来更新 checkedKeys 状态
  /*
  * 当组件接收到新的属性时调用
  * */
  componentWillReceiveProps (nextProps) {
    const menus = nextProps.role.menus
    this.setState({ checkedKeys: menus})
  }

  render () {
    const { role } = this.props
    const { checkedKeys } = this.state

    // 指定 Item 布局的配置对象
    const formItemLayout = {
      labelCol: { // 左侧 label 的宽度
        xs: { span: 24 },
        sm: { span: 6},
      },
      wrapperCol: { // 右侧包裹的宽度
        xs: { span: 24 },
        sm: { span: 16 },
      },
    }

    return (
      <div>
        <Item label='角色名称' {...formItemLayout}>
          <Input value={role.name} disabled />
        </Item>
        <Tree
          checkable
          defaultExpandAll={true}
          checkedKeys={checkedKeys}
          onCheck={this.onCheck}
        >
          {
            this.treeNodes
          }
        </Tree>
      </div>
    )
  }
}
